﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using br.com.SistemaChamados.Controller;
using br.com.SistemaChamados.Model;
using br.com.SistemaChamados.Model.Common;
using br.com.SistemaChamados.Enum;
using System.Text;
using System.Web.Security;
using br.com.SistemaChamados.Controller.Common;
using br.com.SistemaChamados.Constants;
using br.com.SistemaChamados.Util;


public partial class Pages_CallRouting : System.Web.UI.Page
{

    private const string SESSION_USER_ID = "userLoggedIn";
    private const string SESSION_CALL_ID = "idCall";

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        ViewStateUserKey = Session.SessionID;
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        br.com.SistemaChamados.Model.Common.User loggedUser = new br.com.SistemaChamados.Model.Common.User();
        UserController userController = new UserController();
        if (Session[UserConstants.SESSION_USER_LOGGED_IN] != null)
        {
            loggedUser.Id = Convert.ToInt32(Session[UserConstants.SESSION_USER_LOGGED_IN]);
            loggedUser = userController.GetUser(loggedUser);
            this.MasterPageFile = MasterPageDefiner.defineMasterPageByAccessRole(loggedUser.Profile);
            ((Label)Master.FindControl("lblUser")).Text = loggedUser.Name;
            this.Title = "SysCall - Sistema de chamados [logado como " + loggedUser.Name + "]";
        }
        else
        {
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (User.IsInRole("ADMIN") || User.IsInRole("ANALYST"))
        {
            if (!IsPostBack)
            {
                rblCallStatus.SelectedValue = "Encaminhar";
                string id = Session[SESSION_CALL_ID].ToString();
                Call callRouting = new Call();
                Call returnedCall = new Call();
                callRouting.Id = Convert.ToInt32(id);
                CallController controller = new CallController();
                returnedCall = controller.GetCall(callRouting);
                if (returnedCall.Annex != null && returnedCall.Annex.Count > 0)
                {
                    fillLtbAnnex(returnedCall.Annex);
                }
                tryPopulateVars(returnedCall);
            }
        }
        else
        {
            FormsAuthentication.SignOut();
            Response.Clear();
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    private void tryPopulateVars(Call returnedCall)
    {
        try
        {
            if (returnedCall != null)
            {
                lblUserOpen.Text = returnedCall.UserOpen.Name;
                lblEMailOpen.Text = returnedCall.UserOpen.EMail;
                lblUnit.Text = returnedCall.Sector.Unit.Name;
                lblSector.Text = returnedCall.Sector.Description;
                lblOpen.Text = String.Format("{0:dd/mm/yyyy}", Convert.ToString(returnedCall.DateOpening));
                txbProblem.Text = returnedCall.ProblemDescription;
                txbSolution.Text = returnedCall.SolutionDescription;
                /*if (returnedCall.Annex != null)
                {
                    Int32 listSize = returnedCall.Annex.Count;
                    Annex getAnnex = new Annex();
                    for (int i = 0; i < listSize; i++)
                    {
                        getAnnex = returnedCall.Annex[i];
                        ltbAnnex.Items.Add(getAnnex.Description);
                    }
                }*/
            }
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro na carga da tela: <br>" + ex.Message +
                               ".');</script>");
        }
    }

    protected void rblCallStatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (rblCallStatus.SelectedValue == "Encaminhar")
        {
            txbjustification.Visible = false;
            lbljustification.Visible = false;
            ddlTechnicalUsers.Visible = true;
        }
        else if (rblCallStatus.SelectedValue == "Fechar")
        {
            ddlTechnicalUsers.Visible = false;
            txbjustification.Visible = true;
            lbljustification.Visible = true;
        }
    }
    protected void btnCallRouting_Click(object sender, EventArgs e)
    {
        string id = Session["idCall"].ToString();
        Call updateCall = new Call();
        updateCall.CallStatus = new CallStatus();
        updateCall.Id = Convert.ToInt32(id);
        if (ddlTechnicalUsers.Visible)
        {
            br.com.SistemaChamados.Model.Common.User userToClose = new br.com.SistemaChamados.Model.Common.User();
            userToClose.Id = Convert.ToInt32(ddlTechnicalUsers.SelectedValue);
            updateCall.UserFinish = userToClose;
        }
        CallStatus status = new CallStatus();
        switch (rblCallStatus.SelectedValue)
        {
            case "Encaminhar":
                status.Id = 2;
                updateCall.CallStatus = status;
                tryUpdateStatus(updateCall, "Encaminhado");
                break;

            case "Fechar":
                status.Id = 3;
                User userClose = new User();
                userClose.Id = Convert.ToInt32(Session[SESSION_USER_ID]);
                updateCall.UserFinish = userClose;
                updateCall.CallStatus = status;
                updateCall.Observation = txbjustification.Text;
                tryUpdateStatus(updateCall, "Fechado");
                break;
        }
    }

    private void tryUpdateStatus(Call updateCall, string action)
    {
        CallController controller = new CallController();
        try
        {
            EnumCRUDState resultOperation = controller.UpdateCall(updateCall);
            if (resultOperation == EnumCRUDState.SQL_SUCCESS)
            {
                Response.Write(@"<script language='javascript'>alert('Chamado " + action + " com sucesso!');</script>");
            }
            else
            {
                Response.Write(@"<script language='javascript'>alert('Ocorreu um erro durante a " + action + ", tente novamente mais tarde!');</script>");
            }
        }
        catch (Exception ex)
        {

            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro na " + action + ": <br>" + ex.Message +
                              ".');</script>");
        }
        finally
        {
            Session.Remove("id");
            updateCall = null;
            Response.Redirect("CallRouteList.aspx");
        }
    }

    protected void ltbAnnex_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            StringBuilder file = new StringBuilder();
            Annex getAnnex = new Annex();
            Annex returnAnnex = new Annex();
            AnnexController controller = new AnnexController();
            int sizeString = ltbAnnex.SelectedValue.Length;
            int search = ltbAnnex.SelectedValue.LastIndexOf("/");
            int x = 0;
            for (int i = (search + 1); i < (sizeString); i++)
            {
                file.Append(ltbAnnex.SelectedValue[i]);
                x++;
            }
            Response.ContentType = "application / " + file;
            Response.AddHeader("content-disposition", "attachment; filename = " + file);
            Response.TransmitFile(@ltbAnnex.SelectedValue);
            Response.End();
        }
        catch (Exception ex) { }
    }

    private void fillLtbAnnex(List<Annex> annex)
    {
        ltbAnnex.DataSource = annex;
        ltbAnnex.DataTextField = "Description";
        ltbAnnex.DataValueField = "Description";
        ltbAnnex.DataBind();
        ltbAnnex.Items.Insert(0, "");
    }
}